package cn.k23.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * @Description:Thymeleaf 配置模板
 * @Author: k23
 * @Date: 2022-03-28 14:43
 * @Version: 1.0
 */
@Configuration
public class ThymeleafConfig {
    @Bean
    public SpringResourceTemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("utf-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        return templateResolver;
    }
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        //处理java8 日期新格式
        templateEngine.addDialect(new Java8TimeDialect());

        return templateEngine;
    }
    @Bean
    @Primary
    /*@Primary:在声明bean的时候，通过将其中一个可选的bean设置为首选*/
    public ThymeleafViewResolver viewResolver() {
        ThymeleafViewResolver view = new ThymeleafViewResolver();
        view.setCharacterEncoding("utf-8");
        view.setOrder(1);
        view.setTemplateEngine(templateEngine());
        return view;
    }

}
